package com.javaee.exep3.service.impl;

import com.javaee.exep3.entity.GlobalMap;
import com.javaee.exep3.entity.RegionStats;
import com.javaee.exep3.entity.RegionStatsVO;
import com.javaee.exep3.service.COVID19MsgService;
import com.javaee.exep3.utils.Date2StringUtils;
import com.javaee.exep3.utils.HTTPUtil;
import com.sun.javafx.UnmodifiableArrayList;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.logging.log4j.util.PropertySource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.comparator.Comparators;

import javax.annotation.PostConstruct;
import javax.swing.plaf.synth.Region;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: lzh
 */
@Service
public class COVID19MsgServiceImpl implements COVID19MsgService {

    @Value("${myconfig.covid-19-csv-url}")
    private String csvUrl;

    List<RegionStats> regionStatsList = new ArrayList<>();

    List<GlobalMap> mapData = new ArrayList<>();

    Integer globalTotalCases = 0;

    Integer globalTotalIncreased = 0;

    @Override
    @Scheduled(cron = "${myconfig.cron}")
    @PostConstruct
    public void getDataFromGit() throws IOException {
        //发送http请求获取csv文件流
        Resource resource = HTTPUtil.sendHttp(csvUrl);
        InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream());
        //解析csv文件
        CSVParser parser = CSVFormat.DEFAULT.withHeader().withSkipHeaderRecord().parse(inputStreamReader);
        for (CSVRecord record : parser.getRecords()) {
            RegionStats regionStates = new RegionStats();
            GlobalMap globalMap = new GlobalMap();
            ArrayList<String> value = new ArrayList<>();
            //获取昨天新增数
            Integer yesterday = Integer.valueOf(record.get(record.size() - 1));
            Integer beforeYesterday = Integer.valueOf(record.get(record.size() - 2));
            Integer diff = yesterday - beforeYesterday;
            //设置每个州的信息
            regionStates.setDiffFromPrevDay(diff);
            regionStates.setState(record.get("Province/State"));
            regionStates.setCountry(record.get("Country/Region"));
            regionStates.setLatestTotalCases(yesterday);
            //设置地图数据信息
            String name = regionStates.getState().length() != 0 ? regionStates.getState() : regionStates.getCountry();
            globalMap.setName(name);
            globalMap.setCountry(regionStates.getCountry());
            value.add(record.get("Long"));
            value.add(record.get("Lat"));
            value.add(record.get(record.size() - 1));
            globalMap.setValue(value);
            mapData.add(globalMap);
            regionStatsList.add(regionStates);
            //更新总数和新增数
            globalTotalCases += yesterday;
            globalTotalIncreased += diff;
        }
    }

    @Override
    public RegionStatsVO getCovid19Msg(String country) {
        RegionStatsVO regionStatsVO = new RegionStatsVO();
        Integer totalCases = 0;
        Integer totalIncreased = 0;
        if(country != null) {
            List<RegionStats> collect = regionStatsList.stream()
                    .filter(regionStats -> regionStats.getCountry().compareTo(country) == 0)
                    .collect(Collectors.toList());
            if(collect.size() == 0) {
                regionStatsVO.setRegion("Global");
                regionStatsVO.setLatestTotalCases(globalTotalCases);
                regionStatsVO.setDiffFromPrevDay(globalTotalIncreased);
            } else {
                for (RegionStats regionStats : collect) {
                    totalCases += regionStats.getLatestTotalCases();
                    totalIncreased += regionStats.getDiffFromPrevDay();
                    regionStatsVO.setLatestTotalCases(totalCases);
                    regionStatsVO.setDiffFromPrevDay(totalIncreased);

                }
                regionStatsVO.setRegion(country);
            }
            regionStatsVO.setRegionStatsList(collect);

        } else {
            regionStatsVO.setRegion("Global");
            regionStatsVO.setLatestTotalCases(globalTotalCases);
            regionStatsVO.setDiffFromPrevDay(globalTotalIncreased);
            regionStatsVO.setRegionStatsList(regionStatsList);
        }
        regionStatsVO.setMapData(mapData);
        return regionStatsVO;
    }
}
